package com.whzykj.ctrl;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.whzykj.alipay.config.AlipayConfig;
import com.whzykj.alipay.util.AlipayCore;
import com.whzykj.alipay.util.AlipayNotify;
import com.whzykj.common.AmountUtils;
import com.whzykj.common.CommonUtils;
import com.whzykj.common.DateUtil;
import com.whzykj.common.alipay.AliPayConst;
import com.whzykj.common.wx.WxConst;
import com.whzykj.common.wx.XMLUtil;
import com.whzykj.model.Account;
import com.whzykj.model.PayLog;
import com.whzykj.model.Userinfo;
import com.whzykj.model.VirtualOrder;
import java.net.URLDecoder;

public class AliPayController extends Controller{

	/**
	 * 支付宝订单支付回调
	 * 支付结果
	 * */
	public void payresult() {
		
		System.out.print("支付宝支付回调获取数据开始");
		
		//AlipayCore.logResult(getPara("out_trade_no"),"notify_url");
		//AlipayCore.logResult(getPara("trade_no"),"notify_url");
		//AlipayCore.logResult(getPara("trade_status"),"notify_url");
		//AlipayCore.logResult(getPara("total_amount"),"notify_url");
		//AlipayCore.logResult(getPara("gmt_payment"),"notify_url");
		
		System.out.print("支付宝支付回调获取数据开始==================》余额支付");
		
		System.out.println("===============================================================================:"+getPara("out_trade_no"));
		System.out.println("===============================================================================:"+getPara("trade_no"));
		System.out.println("===============================================================================:"+getPara("trade_status"));
		System.out.println("===============================================================================:"+getPara("total_amount"));
		System.out.println("===============================================================================:"+getPara("gmt_payment"));
		System.out.println("???????????????????????????????????????????????????passback_params===========================================:"+getPara("passback_params"));

		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = getRequest().getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		System.out.println("======================================URL 20161110=========================================:"+AlipayCore.createLinkString(params));
		//AlipayCore.logResult(AlipayCore.createLinkString(params),"notify_url");
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		String out_trade_no="";
		String trade_no="";
		String trade_status="";
		String total_amount="";
		String gmt_payment="";
		String passback_params="";
		try {
			
			//商户订单号	
			 out_trade_no = new String(getPara("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
			 System.out.println("???????????????????????????????????????????????????out_trade_no===========================================:"+out_trade_no);
			 
			//支付宝交易号	
			 trade_no = new String(getPara("trade_no").getBytes("ISO-8859-1"),"UTF-8");
			 System.out.println("???????????????????????????????????????????????????trade_no===========================================:"+trade_no);

			//交易状态
			 trade_status = new String(getPara("trade_status").getBytes("ISO-8859-1"),"UTF-8");
			 System.out.println("???????????????????????????????????????????????????trade_status===========================================:"+trade_status);
			 
			//订单金额
			 total_amount = new String(getPara("total_amount").getBytes("ISO-8859-1"),"UTF-8");
			 System.out.println("???????????????????????????????????????????????????total_amount============================================:"+total_amount);
				//交易付款时间
			 gmt_payment = new String(getPara("gmt_payment").getBytes("ISO-8859-1"),"UTF-8");
			 System.out.println("???????????????????????????????????????????????????gmt_payment============================================:"+gmt_payment);
			 
			 //公共回传参数
			 passback_params=getPara("passback_params");
			 passback_params = URLDecoder.decode(passback_params,"utf-8");
			 System.out.println("???????????????????????????????????????????????????passback_params===========================================:"+passback_params);

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//异步通知ID
		String notify_id=getPara("notify_id");
		//sign
		String sign=getPara("sign");
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		if(notify_id!=""&&notify_id!=null){////判断接受的post通知中有无notify_id，如果有则是异步通知。
			if(AlipayNotify.verifyResponse(notify_id).equals("true"))//判断成功之后使用getResponse方法判断是否是支付宝发来的异步通知。
			{
				if(AlipayNotify.getSignVeryfy(params, sign))//使用支付宝公钥验签
				{
					//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
					if(trade_status.equals("TRADE_FINISHED")){
						//判断该笔订单是否在商户网站中已经做过处理
							//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
							//如果有做过处理，不执行商户的业务程序
						//注意：
						//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
						//请务必判断请求时的out_trade_no、total_fee、seller_id与通知时获取的out_trade_no、total_fee、seller_id为一致的
						
					} else if (trade_status.equals("TRADE_SUCCESS")){
						//判断该笔订单是否在商户网站中已经做过处理
							//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
							//如果有做过处理，不执行商户的业务程序
						//注意：
						//付款完成后，支付宝系统发送该交易状态通知
						//请务必判断请求时的out_trade_no、total_fee、seller_id与通知时获取的out_trade_no、total_fee、seller_id为一致的
						
						//判断支付已记录
						PayLog plog = PayLog.me.findFirst("select 1 from pay_log where pay_no = '"+trade_no+"' and status = '00A' ");
						if (plog != null) {
							renderText("success");
							return;
						}
						
						/******
						 * wsh
						 * 16.11.02
						 * 通过out_trade_no查询虚拟订单
						 */
						String sql=" SELECT r.cust_id,r.user_id,a.acct_id FROM orderinfo r,account a WHERE r.cust_id=a.cust_id and r.order_id='"+out_trade_no+"' ";
						Record orderrd = Db.findFirst(sql);
						//客户ID
						String cust_id = String.valueOf(orderrd.getInt("cust_id"));
						//账户ID
						String acct_id = String.valueOf(orderrd.getInt("acct_id"));
						//用户ID
						String user_id = String.valueOf(orderrd.getInt("user_id"));
						
						//Record userinofRd = Userinfo.dao.userInfo(user_id);
						//String station_id = String.valueOf(userinofRd.get("station_id"));
						System.out.println("???????????????????????????????????????????????????balance_pay_amount==========================1==================:"+passback_params);
						//公共回传参数: user_id + "|" + balance_pay
						String[] sid_gid = passback_params.split("\\|");
						String balance_pay_amount = sid_gid[1];
						System.out.println("???????????????????????????????????????????????????balance_pay_amount============================================:"+balance_pay_amount);
						
						//保存到支付记录
						PayLog paylog = new PayLog();
						paylog.set("user_id", user_id);
						paylog.set("open_id", "");
						paylog.set("pay_no", trade_no);
						paylog.set("pay_method", "2");
						paylog.set("create_time",  gmt_payment);
						paylog.set("amount", total_amount);
						paylog.set("status", "00A");
						paylog.set("source_xml", AlipayCore.createLinkString(params));
						paylog.set("remark", "");
						paylog.set("out_trade_no", out_trade_no);
						paylog.save();
						
						//先完成充值流程
						Map<String,Object> paraMap =new HashMap<String,Object>();
						paraMap.put("acct_id", acct_id);
						paraMap.put("recharge_type", "02");
						paraMap.put("buyer_login_id", "");
						paraMap.put("bank_type", "");
						paraMap.put("bank_name", "");
						paraMap.put("tid", trade_no);
						paraMap.put("app_id", AliPayConst.appid);
						paraMap.put("out_trade_no", out_trade_no);
						paraMap.put("amount", total_amount);
						//时间类型转
						String  time_end= DateUtil.getDateByStr(gmt_payment);
						paraMap.put("time_end", DateUtil.getDateStr(time_end));
						paraMap.put("cust_id", cust_id);
						paraMap.put("userid", user_id);
						//paraMap.put("station_id", station_id);
						//完成充值流程
						boolean rechargestatus = Account.dao.recharge(paraMap);
						System.out.println("???????????????????????????????????????????????????rechargestatus============================================:"+rechargestatus);
						
						//再进行扣款流程
						Map<String,Object> payMap =new HashMap<String,Object>();
						payMap.put("cust_id", cust_id);
						payMap.put("online_amount", total_amount);
						payMap.put("balance_pay_amount", balance_pay_amount);
						payMap.put("out_trade_no", out_trade_no);
						payMap.put("user_id", user_id);
						boolean paystatus = Account.dao.pay(payMap);
						System.out.println("???????????????????????????????????????????????????paystatus============================================:"+paystatus);
						//完成充值流程
						if(paystatus && rechargestatus){
							renderText("success");
						}
					}
					//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
					//out.print("success");//请不要修改或删除
					//renderText("success");
					//调试打印log
					//AlipayCore.logResult("notify_url success!","notify_url");
				}
				else//验证签名失败
				{
					//out.print("sign fail");
					renderText("sign fail");
				}
			}
			else//验证是否来自支付宝的通知失败
			{
				//out.print("response fail");
				renderText("response fail");
			}
		}else{
			//out.print("no notify message");
			renderText("no notify message");
		}
	}
	
	public void test(){
		
		//再进行扣款流程
		Map<String,Object> payMap =new HashMap<String,Object>();
		payMap.put("cust_id", "7");
		payMap.put("online_amount", "0.01");
		payMap.put("balance_pay_amount", "0.01");
		payMap.put("out_trade_no", "APP20161110160957240");
		payMap.put("user_id", "23");
		boolean paystatus = Account.dao.pay(payMap);
		
	}
	
	
	/**
	 * 支付宝余额充值回调
	 * 支付结果
	 * */
	public void balancepayresult(){
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = getRequest().getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			
			System.out.println("=======================================valueStr========================================:"+valueStr);
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		System.out.println("=======================================params========================================:"+params);
		
		//AlipayCore.logResult(getPara("out_trade_no"),"notify_url");
		//AlipayCore.logResult(getPara("trade_no"),"notify_url");
		//AlipayCore.logResult(getPara("trade_status"),"notify_url");
		//AlipayCore.logResult(getPara("total_amount"),"notify_url");
		//AlipayCore.logResult(getPara("gmt_payment"),"notify_url");
		
		System.out.print("支付宝支付回调获取数据开始==================》余额支付");
		
		System.out.println("===============================================================================:"+getPara("out_trade_no"));
		System.out.println("===============================================================================:"+getPara("trade_no"));
		System.out.println("===============================================================================:"+getPara("trade_status"));
		System.out.println("===============================================================================:"+getPara("total_amount"));
		System.out.println("===============================================================================:"+getPara("gmt_payment"));

		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		
		System.out.println("======================================URL 20161110=========================================:"+AlipayCore.createLinkString(params));
		//AlipayCore.logResult(AlipayCore.createLinkString(params),"notify_url");
		
		String out_trade_no="";
		String trade_no="";
		String trade_status="";
		String total_amount="";
		String gmt_payment="";
		try {
			
			//商户订单号	
			 out_trade_no = new String(getPara("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
			 
			 System.out.println("=====================out_trade_no=================:"+out_trade_no);
			 
			 //AlipayCore.logResult(out_trade_no,"notify_url");
			
			//支付宝交易号	
			 trade_no = new String(getPara("trade_no").getBytes("ISO-8859-1"),"UTF-8");
			 System.out.println("=====================trade_no=================:"+trade_no);

			//交易状态
			 trade_status = new String(getPara("trade_status").getBytes("ISO-8859-1"),"UTF-8");
			 System.out.println("=====================trade_status=================:"+trade_status);
			 
			//订单金额
			 total_amount = new String(getPara("total_amount").getBytes("ISO-8859-1"),"UTF-8");
			 System.out.println("=====================total_amount=================:"+total_amount);
				//交易付款时间
			 gmt_payment = new String(getPara("gmt_payment").getBytes("ISO-8859-1"),"UTF-8");
			 System.out.println("=====================gmt_payment=================:"+gmt_payment);

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderText("fail");
		}
		
		//异步通知ID
		String notify_id=getPara("notify_id");
		
		System.out.println("=====================notify_id=================:"+notify_id);
		//AlipayCore.logResult(notify_id,"notify_url");
		
		
		//sign
		String sign=getPara("sign");
		
		//System.out.println("=====================sign=================:"+sign);
		//AlipayCore.logResult(sign,"notify_url");
		
		System.out.println("=====================AlipayNotify.verifyResponse(notify_id)=================:"+AlipayNotify.verifyResponse(notify_id).equals("true"));
		
		
		
		System.out.println("=====================AlipayNotify.getSignVeryfy(params, sign)=================:"+AlipayNotify.getSignVeryfy(params, sign));
		
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		
		if(notify_id!=""&&notify_id!=null){////判断接受的post通知中有无notify_id，如果有则是异步通知。
			if(AlipayNotify.verifyResponse(notify_id).equals("true"))//判断成功之后使用getResponse方法判断是否是支付宝发来的异步通知。
			{
				if(AlipayNotify.getSignVeryfy(params, sign))//使用支付宝公钥验签
				{
					//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
					if(trade_status.equals("TRADE_FINISHED")){
						//判断该笔订单是否在商户网站中已经做过处理
							//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
							//如果有做过处理，不执行商户的业务程序
						//注意：
						//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
						//请务必判断请求时的out_trade_no、total_fee、seller_id与通知时获取的out_trade_no、total_fee、seller_id为一致的
						
					} else if (trade_status.equals("TRADE_SUCCESS")){
						//判断该笔订单是否在商户网站中已经做过处理
							//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
							//如果有做过处理，不执行商户的业务程序
						//注意：
						//付款完成后，支付宝系统发送该交易状态通知
						//请务必判断请求时的out_trade_no、total_fee、seller_id与通知时获取的out_trade_no、total_fee、seller_id为一致的
						
						//判断支付已记录
						PayLog plog = PayLog.me.findFirst("select 1 from pay_log where pay_no = '"+trade_no+"' and status = '00A' ");
						if (plog != null) {
							renderText("success");
							return;
						}
						
						/******
						 * wsh
						 * 16.11.02
						 * 通过out_trade_no查询虚拟订单
						 */
						VirtualOrder order = VirtualOrder.dao.findById(out_trade_no);
						order.set("status", "PAID");//虚拟订单修改成已支付
						order.update();
						//客户ID
						String cust_id = String.valueOf(order.getInt("cust_id"));
						//账户ID
						String acct_id = String.valueOf(order.getInt("acct_id"));
						//用户ID
						String user_id = String.valueOf(order.getInt("user_id"));
						
						Record userinofRd = Userinfo.dao.userInfo(user_id);
						String station_id = String.valueOf(userinofRd.get("station_id"));
						
						//保存到支付记录
						PayLog paylog = new PayLog();
						paylog.set("user_id", user_id);
						paylog.set("open_id", "");
						paylog.set("pay_no", trade_no);
						paylog.set("pay_method", "2");
						paylog.set("create_time",  gmt_payment);
						paylog.set("amount", total_amount);
						paylog.set("status", "00A");
						paylog.set("source_xml", AlipayCore.createLinkString(params));
						paylog.set("remark", "");
						paylog.set("out_trade_no", out_trade_no);
						paylog.save();
						
						//先完成充值流程
						Map<String,Object> paraMap =new HashMap<String,Object>();
						paraMap.put("acct_id", acct_id);
						paraMap.put("recharge_type", "02");
						paraMap.put("buyer_login_id", "");
						paraMap.put("bank_type", "");
						paraMap.put("bank_name", "");
						paraMap.put("tid", trade_no);
						paraMap.put("app_id", AliPayConst.appid);
						paraMap.put("out_trade_no", out_trade_no);
						paraMap.put("amount", total_amount);
						//时间类型转
						String  time_end= DateUtil.getDateByStr(gmt_payment);
						paraMap.put("time_end", DateUtil.getDateStr(time_end));
						paraMap.put("cust_id", cust_id);
						paraMap.put("userid", user_id);
						paraMap.put("station_id", station_id);
						
						//完成充值流程
						boolean rechargestatus = Account.dao.balancerecharge(paraMap);
						if(rechargestatus){
							renderText("success");
						}
					}
					//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
					//out.print("success");//请不要修改或删除
					//renderText("success");
					//调试打印log
					//AlipayCore.logResult("notify_url success!","notify_url");
				}
				else//验证签名失败
				{
					//out.print("sign fail");
					renderText("sign fail");
				}
			}
			else//验证是否来自支付宝的通知失败
			{
				//out.print("response fail");
				renderText("response fail");
			}
		}else{
			//out.print("no notify message");
			renderText("no notify message");
		}
	}
}
